﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace Foundation
{
    [DataContract]
    public static class Store
    {
        private static readonly Dictionary<Type, object> Dictionary = new Dictionary<Type, object>();

        public static TItem OfType<TItem>(params object[] args) where TItem : class
        {
            var itemType = typeof (TItem);
            if (!Dictionary.ContainsKey(itemType))
            {
                var hasDataContract = Attribute.IsDefined(itemType, typeof (DataContractAttribute));
                var item = hasDataContract
                               ? Serializer.TryDeserializeDataContract<TItem>() ??
                                 (TItem) Activator.CreateInstance(itemType, args)
                               : (TItem) Activator.CreateInstance(itemType, args);
                lock (Dictionary) // protection from recursively creating
                    if (!Dictionary.ContainsKey(itemType))
                        Dictionary.Add(itemType, item);
            }

            return (TItem) Dictionary[itemType];
        }
    }
}
